package com.itic.mall.mobile.hongbao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.certproduct.persistence.model.CertProduct;
import com.itic.mall.system.certproduct.persistence.model.CertProductExample;
import com.itic.mall.system.certproduct.service.CertProductService;
import com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecord;
import com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecordExample;
import com.itic.mall.system.hongbaorecord.service.HongbaoRecordService;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.user.persistence.model.MallUser;


/**
 * 友惠家商城中心接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/hongbao")
public class MallHongbaoInterface
     extends BaseMobileInterface {
   @Autowired
   private HongbaoRecordService hongbaoRecordService;
   @Autowired
   private ProductService productService;
   @Autowired
   private CertProductService certProductService;
   
   /**
    * 获取跳转到红包页面
    * @return
    */
   @RequestMapping(value="/index")
   @ResponseBody
   public Map<String,Object> index(HttpServletRequest request,HttpServletResponse response,String token, String productId){
   	Map<String, Object> resultMap = new HashMap<String,Object>();
   	String result = FAIL;
   	String errorCode = PARAM_ERROR_CODE;
   	String errorMsg = PARAM_ERROR_MSG;
   	try{
   		if( StringHelper.isNotBlank(productId) ){
   			MallUser user = getMallUserByToken(token);
   			if( null != user ){
   				Map<String, Object> dataMap = new HashMap<String,Object>();
   				
   				Product product = productService.get(productId);
   				if( null != product ){
   					String productHongbao = getHongbao(product);
   	   	   			product.setProductHongbao(productHongbao);
   	   	   			product.setProductPrice(getProdcutPrice(product));
   	   	   			//判断 用户是否领取过红包
   	   	   			String haveHongbao = isHaveHongbao(user.getId(), productId);
   	   	   			
   	   	   			dataMap.put("hongbao", productHongbao);
   	   	   			dataMap.put("isLingqu", haveHongbao);
   	   	   			dataMap.put("product", product);
   	   	   			dataMap.put("content", "test");
   	   	   			
   	   	   			String start = DateHelper.formatDate(DateHelper.getDateByStringDateYYYYMMDD(product.getStartTime()), "yyyy/MM/dd");
   	   	   			String stop = DateHelper.formatDate(DateHelper.getDateByStringDateYYYYMMDD(product.getStopTime()), "yyyy/MM/dd");
   	   	   			dataMap.put("time", start+"-"+stop);
   	   	   			resultMap.put(DATA, dataMap);
   		   	   		result = SUCCESS;
   		   			errorCode = SUCCESS_ERROR_CODE;
   		   	       	errorMsg = SUCCESS_ERROR_MSG; 
   				}else{
   		   			errorCode = PRODUCT_NULL_ERROR_CODE;
   		   	       	errorMsg = PRODUCT_NULL_ERROR_MSG; 
   				}
   			}else{
   				result = LOGIN;
   				errorCode = LOGIN_ERROR_CODE;
   		       	errorMsg = LOGIN_ERROR_MSG;    
   			}
   		}
       	
   	}catch(Exception e){
   		errorCode = SERVER_ERROR_CODE;
       	errorMsg = SERVER_ERROR_MSG;
       	logException("MallCompanyInterface", "phone", e.toString(),"获取客服电话",e);
   	}
   	resultMap.put(RESULT, result);
   	resultMap.put(ERROR_CODE, errorCode);
   	resultMap.put(ERROR_MSG, errorMsg);
   	isCrrossDomain(response);
   	return resultMap;
   } 
   
    /**
     * 用户领取红包方法
     * @return
     */
    @RequestMapping(value="/get")
    @ResponseBody
    public Map<String,Object> get(HttpServletRequest request,HttpServletResponse response,String token,String productId){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(productId) ){
       			MallUser user = getMallUserByToken(token);
       			if( null != user ){
       				Product product = productService.get(productId);
       				String productHongbao = product.getProductHongbao();
       	   			//判断 用户是否领取过红包
       	   			String haveHongbao = isHaveHongbao(user.getId(), productId);
       	   			//如果有红包，则提示已领取过了
       	   			if( "1".equals(haveHongbao) ){
       	   				result = FAIL;
	       	   			errorCode = LINGQUED_ERROR_CODE;
	    	   	       	errorMsg = LINGQUED_ERROR_MSG; 
       	   			}else{
       	   				//生成红包
       	   				HongbaoRecord hongbaoRecord = new HongbaoRecord();
       	   				hongbaoRecord.setIsUsed("0");
       	   				hongbaoRecord.setUserId(user.getId());
       	   				hongbaoRecord.setProductId(productId);
       	   				hongbaoRecord.setMoney(Integer.parseInt(productHongbao));
       	   				//hongbaoRecord.setExpiredTime(DateHelper.addWeeks(new Date(), 1));//默认有效期时间为一周
       	   				hongbaoRecord.setStartTime(product.getStartTime());
       	   				hongbaoRecord.setStopTime(product.getStopTime());
       	   			    result = hongbaoRecordService.add(hongbaoRecord);
       	   			    updateUserCertProduct(user.getId(),productId);
	    	   			errorCode = SUCCESS_ERROR_CODE;
	    	   	       	errorMsg = SUCCESS_ERROR_MSG; 
       	   			}
       			}else{
       				result = LOGIN;
       				errorCode = LOGIN_ERROR_CODE;
       		       	errorMsg = LOGIN_ERROR_MSG;    
       			}
       		} 
        	
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	logException("MallCompanyInterface", "phone", e.toString(),"获取客服电话",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    public void updateUserCertProduct( String userId, String productId ){
    	 //更新用户购物中的商品信息
		CertProductExample example = new CertProductExample();
	    example.createCriteria().andUserIdEqualTo(userId).andProductIdEqualTo(productId);
	    List<CertProduct> list = certProductService.list(example);
	    if( list.size() > 0 ){
	    	for( CertProduct tmp : list ){
	    		String oriPrice = tmp.getProductOrginPrice();
	    		String hongbao = tmp.getProductHongbao();
	    		String price = NumberStringHelper.subtractString(oriPrice, hongbao);
	    		tmp.setProductPrice(price);
	    		
	    		certProductService.edit(tmp);
	    	}
	    }
    }
   
    /**
     * 用户领取红包方法
     * @return
     */
    @RequestMapping(value="/list")
    @ResponseBody
    public Map<String,Object> list(HttpServletRequest request,HttpServletResponse response,String token ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(token) ){
       			MallUser user = getMallUserByToken(token);
       			if( null != user ){
       				
       				HongbaoRecordExample example = new HongbaoRecordExample();
       				com.itic.mall.system.hongbaorecord.persistence.model.HongbaoRecordExample.Criteria criteria = example.createCriteria();
       				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
       				criteria.andUserIdEqualTo(user.getId());
       				
       				List<HongbaoRecord> list = hongbaoRecordService.list(example);
       				List<HongbaoVo> hongbaos = new ArrayList<HongbaoVo>();
       				if( list.size()>0 ){
       					for( HongbaoRecord tmp : list ){
       						Product product = productService.get(tmp.getProductId());
       						HongbaoVo vo = new HongbaoVo();
       						vo.setId(tmp.getId());
       						vo.setMainImgUrl(product.getMainImageUrl());
       						vo.setName(product.getName());
       						vo.setOrginPrice(product.getProductOrginPrice());
       						vo.setHongbao(tmp.getMoney()+"");
       						vo.setPrice(NumberStringHelper.subtractString(product.getProductOrginPrice(), tmp.getMoney()+""));
       						vo.setTime(tmp.getStartTime()+"~"+tmp.getStopTime());
       						vo.setProductId(tmp.getProductId());
       						hongbaos.add(vo);
       					}
       				}
       				resultMap.put(DATA, hongbaos);
       				result = SUCCESS;
       				errorCode = SUCCESS_ERROR_CODE;
       		       	errorMsg = SUCCESS_ERROR_MSG; 
       			}else{
       				result = LOGIN;
       				errorCode = LOGIN_ERROR_CODE;
       		       	errorMsg = LOGIN_ERROR_MSG;    
       			}
       		} 
        	
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	logException("MallCompanyInterface", "phone", e.toString(),"获取客服电话",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
    
    /**
     * 用户领取红包方法
     * @return
     */
    @RequestMapping(value="/del")
    @ResponseBody
    public Map<String,Object> del(HttpServletRequest request,HttpServletResponse response,String token ,String id ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(id) ){
       			MallUser user = getMallUserByToken(token);
       			if( null != user ){
       				HongbaoRecord hongbaoRecord = new HongbaoRecord();
       				hongbaoRecord.setId(id);
       				hongbaoRecordService.delete(hongbaoRecord);
       				result = SUCCESS;
       				errorCode = SUCCESS_ERROR_CODE;
       		       	errorMsg = SUCCESS_ERROR_MSG; 
       			}else{
       				result = LOGIN;
       				errorCode = LOGIN_ERROR_CODE;
       		       	errorMsg = LOGIN_ERROR_MSG;    
       			}
       		} 
        	
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	logException("MallCompanyInterface", "phone", e.toString(),"获取客服电话",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    } 
    
   
}